package edu.task.repository;

import edu.task.model.SysRole;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface SysRoleRepository extends JpaRepository<SysRole, Long> {

    final String SELECT = "select distinct r.* from sys_role r ";
    final String JOIN_USER_ROLE=" left join sys_user_role ur on ur.role_id = r.role_id ";
    final String JOIN_USER=" left join sys_user u on u.user_id = ur.user_id ";


    @Query(value = "select r.role_id from sys_role r " +JOIN_USER_ROLE+JOIN_USER+
            "WHERE r.del_flag='0' and u.user_id=:userId",nativeQuery = true)
    List<Long> selectRoleIdsByUserId(Long userId);


    @Modifying
    @Query(value = "update sys_role set del_flag='1' where role_id in :roleIds",nativeQuery = true)
    int deleteUserByIds(Long[] roleIds);


    @Query(value = "select * from sys_role where del_flag='0'",nativeQuery = true)
    List<SysRole> selectRoleList() ;

    @Modifying
    @Query(value = " delete rm from sys_role_menu as rm " +
            "inner join sys_role as r on rm.role_id = r.role_id " +
            "inner join sys_menu as m on rm.menu_id = m.menu_id " +
            "where rm.role_id=:roleId ", nativeQuery = true)
    int deleteRoleMenuByRoleId(Long roleId);


    @Query(value = "select r.role_id from sys_role as r " +
            "inner join sys_user_role as ur on ur.role_id = r.role_id " +
            "inner join sys_user as u on u.user_id = ur.user_id " +
            "WHERE r.del_flag='0' and ur.user_id=:userId",nativeQuery = true)
    List<SysRole> selectRoleByUserId(Long userId);
}
